﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Printing;
using Newtonsoft.Json;
using System.IO;
using PdfiumViewer;
using System.Runtime.InteropServices;

namespace SocketClient
{
    class PrintPdf
    {
        public BindingList<WomWorkOrderItemPage> opDatas = null;
        public List<String> productCodes = new List<string>();
        public Dictionary<String, WomWorkOrderItemPage> woMap = new Dictionary<string, WomWorkOrderItemPage>();
        //public static void LaunchFrontendApp()
        //{
        //    // 启动前端程序
        //    Process.Start("FrontendApp.exe");

        //    // 将前端程序置于最前
        //    SetForegroundWindow(GetProcessHandle("FrontendApp.exe"));
        //}

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        private static IntPtr GetProcessHandle(string processName)
        {
            Process[] processes = Process.GetProcessesByName(processName);
            if (processes.Length > 0)
            {
                return processes[0].MainWindowHandle;
            }
            return IntPtr.Zero;
        }
        public enum ShowWindowCommands : int
        {
            SW_HIDE = 0,
            SW_SHOWNORMAL = 1,
            SW_NORMAL = 1,
            SW_SHOWMINIMIZED = 2,
            SW_SHOWMAXIMIZED = 3,
            SW_MAXIMIZE = 3,
            SW_SHOWNOACTIVATE = 4,
            SW_SHOW = 5,       //显示一个窗口，同时令其进入活动状态
            SW_MINIMIZE = 6,
            SW_SHOWMINNOACTIVE = 7,
            SW_SHOWNA = 8,
            SW_RESTORE = 9,
            SW_SHOWDEFAULT = 10,
            SW_MAX = 10
        }

        [DllImport("kernel32.dll")]
        public static extern int WinExec(string programPath, int operType);
        public void orderprint(String workorderNo)
        {
            getOpDatalist(workorderNo);
        }

        private OpmOutsourceProcessPage getOpDatalist(String outSourceNo)
        {
            OpmOutsourceProcessPage opm = new OpmOutsourceProcessPage();

            //获取到了token
            Http.CreateHttpClient(GValues.tenant, GValues.token).GetAsync(GValues.domainLink + "wom/womWorkOrder/list?queryName=" + outSourceNo, new Action<Http.HttpResp>((r2) =>
            {
                //OutputMsg outMsg = new OutputMsg();
                var responCode = Convert.ToInt32(r2.Code);
                if (responCode == 200) //访问成功
                {
                    ResponResultA<WomWorkOrderItemPage> cc = JsonConvert.DeserializeObject<ResponResultA<WomWorkOrderItemPage>>(r2.AckStr());
                    if (cc.success)
                    {
                        if (cc.result.records.Count > 0)
                        {
                            try
                            {
                                woMap = new Dictionary<string, WomWorkOrderItemPage>();
                                opDatas = cc.result.records;
                                woMap.Add(opDatas[0].workOrderNumber, opDatas[0]);
                                productCodes.Add(opDatas[0].code);
                                foreach (WomWorkOrderItemPage item in opDatas[0].itemChilds)
                                {
                                    woMap.Add(item.workOrderNumber, item);
                                    productCodes.Add(item.code);
                                }
                                createPdfAddQRcode(productCodes);
                                 LogHelper.WriteLog("获取工单成功！");
                            }
                            catch (Exception e)
                            {
                                LogHelper.WriteLog("转换数据错误！" + e.Message,null);
                            }
                        }
                        else
                        {
                             LogHelper.WriteLog("数据没找到！",null);
                        }

                    }
                    else
                    {
                         LogHelper.WriteLog("数据获取失败！" + cc.message,null);
                    }
                }
                else
                {
                     LogHelper.WriteLog("网络连接错误！" + r2.Error,null);
                }
            }));

            return opm;
        }
        private void createPdfAddQRcode(List<String> productCodes)
        {
            //OutputMsg outMsg = new OutputMsg();
            try
            {
                 LogHelper.WriteLog("转换pdf开始！");
                if (Directory.Exists(@"c:\destination_directory"))
                {
                    Directory.Delete(@"c:\destination_directory", true);
                }
                 LogHelper.WriteLog("查找目录完成！");
                PdfHelper ph = new PdfHelper();
                Dictionary<String, String> map = ph.pdfFileSearchAndCopy(GValues.searchPath, @"c:\destination_directory", woMap);
                List<string> pdfFiles = GetPDFFiles(@"c:\destination_directory");
                // 确保目标目录存在
                Directory.CreateDirectory(@"c:\destination_directory\qrcode");
                 LogHelper.WriteLog("文件拷贝完成！");
                foreach (string file in pdfFiles)
                {
                    String qrText;
                    map.TryGetValue(file, out qrText);
                    WomWorkOrderItemPage item = woMap[qrText];
                    ph.addQRCodeToPdf(file, @"c:\destination_directory\qrcode\" + qrText + ".pdf", qrText + "/" + item.qty);
                }
                Directory.CreateDirectory(@"c:\destination_directory\qrcode\output");
                ph.MergePDFs(@"c:\destination_directory\qrcode", @"c:\destination_directory\qrcode\output", "123");
                this.printPdfViewer(@"c:\destination_directory\qrcode\output\MergedWithPageNumbers.pdf");
            }
            catch (Exception e)
            {
                 LogHelper.WriteLog("获取目录数据错误！" + e.Message);
            }
        }

        public  string ExecuteCommand(string command)
        {
            using (Process process = new Process())
            {
                process.StartInfo.FileName = "cmd.exe";
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;

                process.Start();

                process.StandardInput.WriteLine(command);
                process.StandardInput.WriteLine("exit");

                return process.StandardOutput.ReadToEnd();
            }
        }
        public void printPdfViewer(String inputPdfPathFile)
        {
            //OutputMsg outMsg = new OutputMsg();
            try
            {
                 LogHelper.WriteLog("开始预览pdf！");

                // 或者使用PdfiumViewer来预览PDF
                //using (var document = PdfDocument.Load(inputPdfPathFile))
                //{
                //    using (var render = new PdfRender(document, 0))
                //    {
                //        render.Render(0, render.PageSize.Width, 0, render.PageSize.Height, 96, 96, null, 0);
                //    }
                //}
                //var result = WinExec(@"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe " + inputPdfPathFile, (int)ShowWindowCommands.SW_SHOW);

                //string command = "ipconfig"; // 示例命令
                //string result = ExecuteCommand(command);
                // LogHelper.WriteLog("执行数据pdf！" + result);
                //

                // 打开默认的打印对话框
                //ProcessStartInfo startInfo = new ProcessStartInfo
                //{
                //    FileName = @"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
                //    Arguments = @"E:\MergedWithPageNumbers.pdf",
                //    UseShellExecute = true,
                //    CreateNoWindow = false,
                //    WindowStyle = ProcessWindowStyle.Normal,
                //    Verb = "runas",
                //};
                //Process.Start(startInfo);

                //ServiceInteractiveSession.SetServiceInteractiveSession();
                //WinAPI_Interop.CreateProcess(@"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe");
                //Interops.CreateProcess(@"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe", @"C:\Windows\System32\");
                //第3种
                SessionUtility.CreateProcess("msedge", "", 1);
                //第4种
                //ApplicationLoader.PROCESS_INFORMATION procInfo;
                //ApplicationLoader.StartProcessAndBypassUAC(@"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe", out procInfo);
                //第5种
                //InteropsHelper.CreateProcess("msedge.exe", @"C:\Program Files (x86)\Microsoft\Edge\Application", @" E:\MergedWithPageNumbers.pdf");
                //// 模拟界面交互（例如，等待几秒钟）
                //Thread.Sleep(5000);

                //// 模拟用户点击按钮等操作（使用SendKeys或其他模拟用户输入的方式）
                //SendKeys.SendWait("{ENTER}");
                // 将前端程序置于最前
                //SetForegroundWindow(GetProcessHandle("msedge"));
                 LogHelper.WriteLog("预览pdf结束！");
                //Process process = new Process();

                //process.StartInfo.FileName = "cmd.exe";
                //process.StartInfo.Arguments = "/c dir";
                //process.StartInfo.UseShellExecute = false;
                //process.StartInfo.RedirectStandardOutput = true;
                //process.Start();
                //string output = process.StandardOutput.ReadToEnd();
                //process.WaitForExit();
            }
            catch (Exception e)
            {
                 LogHelper.WriteLog("预览PDF错误！" + e.Message);
            }
        }

        private List<string> GetPDFFiles(string path)
        {
            DirectoryInfo directory = new DirectoryInfo(path);
            FileInfo[] files = directory.GetFiles("*.pdf", SearchOption.TopDirectoryOnly);
            List<string> pdfFiles = new List<string>();

            foreach (FileInfo file in files)
            {
                pdfFiles.Add(file.FullName);
            }

            return pdfFiles;
        }
    }
}
